package com.hytc.controller;

import com.hytc.entity.Cart;
import com.hytc.entity.Product;
import com.hytc.entity.User;
import com.hytc.service.UserService;
import com.hytc.service.impl.UserServiceImpl;
import com.hytc.utils.C3P0Util;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ShoppingServlet extends HttpServlet {
    private UserService service = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         * 将商品添加到购物车
         */
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user!=null){
            int id =Integer.parseInt(request.getParameter("id"));
            String mount = request.getParameter("mount");
            List<Product> list = service.query();
            if(service.add(id,user.getId())) {
                for (Product product : list) {
                    if (id == product.getId()) {
                        service.addcart(product, mount, user.getId());
                        User user1 = (User) session.getAttribute("user");
                        if (user1 != null) {
                            List<Cart> cart = service.cart(user.getId());
                            double sum1 = 0;
                            double sum2 = 0;
                            for (Cart cartItem : cart) {
                                sum1 += cartItem.getBuy_price(); // 折扣金额
                                sum2 += cartItem.getPrice(); // 总金额
                            }

                            // 存储金额信息到会话中
                            session.setAttribute("sum1", sum1 - sum2); // 折扣金额
                            session.setAttribute("sum2", sum2); // 总金额
                            session.setAttribute("cart", cart); // 购物车列表
                        }
                    }
                }
            }else {

            }
            List<Cart> cart = service.cart(user.getId());
            session.setAttribute("cart",cart);
            request.getRequestDispatcher("/buy.jsp").forward(request,response);
        }else {
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }




    }
}
